import {Component, EventEmitter, Output} from '@angular/core';
import {ProductService} from "../../service/product.service";

@Component({
  selector: 'app-dialog-box',
  templateUrl: './dialog-box.component.html',
  styleUrl: './dialog-box.component.css'
})
export class DialogBoxComponent {
    categoryId: string = '';
    productId: string = '';
    itemId: string = '';
    unitCost: string = '';
    listPrice: string = '';
    supplier: string = '';
    _status: string = '';
    description: string = '';

    imageUrl: string | ArrayBuffer | null = null;

    @Output() confirm = new EventEmitter<any>();
    @Output() cancel = new EventEmitter<any>();
    categoryOptions: any;
    productOptions: any;
    supplierOptions: any;
    _statusOptions: any;
    descriptionOptions: any;


    constructor(private productService: ProductService) {
        this.categoryOptions = productService.getCategoryOptions();
        productService.getProductOptions().subscribe(options => {
            this.productOptions = options;
        });
        productService.getSupplierOptions().subscribe(options => {
            this.supplierOptions = options;
        });
        this._statusOptions = productService.getStatusOptions();
        productService.getDescriptionOptions().subscribe(options => {
            this.descriptionOptions = options;
        });
    }

    onCancel() {
        this.cancel.emit();
    }

    onConfirm() {
        const data = {
            categoryId: this.categoryId,
            productId: this.productId,
            itemId: this.itemId,
            unitCost: this.unitCost,
            listPrice: this.listPrice,
            supplier: this.supplier,
            _status: this._status,
            description: this.description,
            imageUrl: this.imageUrl,
        };
        console.log(data);
        this.confirm.emit(data);
    }

    getCategoryId($event: any) {
        console.log($event);
        this.categoryId = $event;
    }

    getProductId($event: any) {
        this.productId = $event;
    }

    getItemId($event: any) {
        this.itemId = $event;
    }

    getUnitCost($event: any) {
        this.unitCost = $event;
    }

    getListPrice($event: any) {
        this.listPrice = $event;
    }

    getSupplier($event: any) {
        this.supplier = $event;
    }

    get_status($event: any) {
        this._status = $event;
    }

    getDescription($event: any) {
        this.description = $event;
    }

    onFileSelected(event: any) {
        const file: File = event.target.files[0];
        if (file && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = () => {
                this.imageUrl = reader.result;
            };
            reader.readAsDataURL(file);
        } else {
            this.imageUrl = "";
            // 如果用户选择的不是图片文件，可以给出提示
            //alert('请选择图片文件！');
        }
    }
}
